package com.atguigu.multiReading;

import static java.lang.Thread.sleep;

/*
1.先实现一个普通队列
2.加上线程安全
3.加上阻塞的实现
 */
public class MyBlockingDeque {
    private int[] array=new int[1000];
    private volatile int head=0;
    private volatile int tail=0;
    private volatile int size=0;
    //入队列
    public void put(int elem) {
        synchronized(this) {
            //判断队列是否已满
            while(size >= array.length) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //进行插入操作，将elem放入到array中
            array[tail] = elem;
            tail++;
            if (tail >= array.length) {
                tail = 0;
            }
            size++;
            notify();
        }
    }
    //出队列，返回被删除的元素
    public Integer take() {
        synchronized (this) {
            //判断队列是否为空
            while (size == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //进行取元素操作
            int tmp = array[head];
            head++;
            if (head >= array.length) {
                head = 0;
            }
            size--;
            notify();
            return tmp;
        }
    }
}
class test{
    public static void main(String[] args) {
        MyBlockingDeque blockingDeque=new MyBlockingDeque();
        Thread thread1=new Thread(()-> {
            int n=1;
                while(true){
                    blockingDeque.put(n);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("生产者"+n);
                    n++;
                }
        });
        Thread thread2=new Thread(()->{
            while(true){
                int n=blockingDeque.take();
                System.out.println("消费者"+n);
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        thread1.start();
        thread2.start();
    }
}
